import axios from 'axios'
import {
    ElLoading,
    ElMessage
} from 'element-plus'
import router from '@/router/index.js'
import 'element-plus/es/components/loading/style/css'
import 'element-plus/es/components/message/style/css'
import _ from 'lodash'

//token检验失败后的提示，使用了节流，防止提示多次
const handlerErrorNo = _.throttle(
    () => {
        router.beforeEach((to, from, next) => {
            if (from.href === '/h5' || from.href === '/trace') {
                return;
            } else {
                ElMessage({
                    message: `token失效，请重新登录`,
                    type: 'error'
                })
            }
        })


        router.push('/login')
    },
    800, {
        leading: true,
        trailing: false
    }
)

const DEFAULT_LOADING = false
//以类的形式封装请求
//以类的形式封装请求有更好的扩展性
class ZHRequest {
    constructor(config) {
        this.instance = axios.create(config)
        this.showLoading = DEFAULT_LOADING
        this.interceptors = config.interceptors

        // 外部添加请求拦截器
        this.instance.interceptors.request.use(
            this.interceptors ?.requestInterceptor,
            this.interceptors ?.requestInterceptorCatch
        )

        //外部添加响应拦截器
        this.instance.interceptors.response.use(
            this.interceptors ?.responseInterceptor,
            this.interceptors ?.responseInterceptorCatch
        )

        //全局拦截器 所有请求都进行拦截
        //全局请求拦截器
        this.instance.interceptors.request.use(
            (config) => {
                this.showLoading = config.showLoading
                if (this.showLoading) {
                    this.loading = ElLoading.service({
                        text: '加载中',
                        body: true,
                        background: 'rgba(0,0,0,0.3)'
                    })
                }
                // console.log('全局请求拦截')
                return config
            },
            (err) => {
                ElMessage({
                    message: err,
                    type: 'error'
                })
                return err
            }
        )
        // 全局响应拦截器
        this.instance.interceptors.response.use(
            (res) => {
                if (res ?.response ?.status == 401) {
                    handlerErrorNo()
                    return false
                }

                // 取消加载动画
                this.loading ?.close()
                this.showLoading = DEFAULT_LOADING
                // console.log('全局响应拦截', res)
                return res.data
            },
            (err) => {
                this.showLoading = DEFAULT_LOADING
                return err
            }
        )
    }

    // 独立的请求拦截
    request(config) {
        return new Promise((resolve, reject) => {
            if (config.interceptors ?.requestInterceptor) {
                if (config.showLoading) {
                    this.showLoading = config.showLoading
                }
                config = config.interceptors.requestInterceptor(config)
            }
            this.instance
            .request(config)
            .then((res) => {
                    if (config.interceptors ?.responseInterceptor) {
                        res = config.interceptors.responseInterceptor(res)
                    }
                    resolve(res)
                })
            .catch((err) => {
                    reject(err)
                })
        })
    }

    get(config) {
        //get(url, {params})
        return this.request({
        ...config,
            method: 'GET'
        })
    }

    post(config) {
        //post(url, data, {params})
        // url必传，data和params二选一传 传data代表以data的方式进行post；传params代表以params的方式进行post
        return this.request({
        ...config,
            method: 'POST'
        })
    }
}
export default ZHRequest